<template>
  <main-content
    :title="applyInfoList.status == 0 ? applyInfoList.title : '商品详情'"
    back
  >
    <template #top>
      <div class="verify-form">
        <div class="verify-form-status">
          <p>审核状态:</p>
          <div>
            <p class="big">
              {{ getVerifyStatus(applyInfoList.status) }}
            </p>
            <!-- <p v-if="applyInfoList.status == 0">提交原因:{{ applyInfoList.title }}</p> -->
            <p v-if="applyInfoList.status == 1 && applyInfoList.applyRemark">
              {{ applyInfoList.applyRemark }}
            </p>
            <p v-else-if="applyInfoList.status == 2">
              {{ applyInfoList.applyRemark }}
            </p>
          </div>
        </div>
        <div class="verify-form-btn">
          <el-button
            v-if="applyInfoList.status == 0"
            type="primary"
            @click="toVerify"
          >
            审核
          </el-button>
        </div>
      </div>
    </template>
    <el-form
      ref="editFormRef"
      :model="editForm"
      status-icon
      label-width="120px"
      class="edit-goods"
    >
      <el-form-item
        label="商品类型"
        prop="type"
      >
        <el-radio-group v-model="editForm.type">
          <el-radio
            v-for="(item, index) in productTypes"
            :key="index"
            :label="item.value"
            disabled
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 非优惠券 -->
      <div v-if="editForm.type != 'discountCoupon'">
        <el-form-item
          label="商品分类"
          prop="productCategoryId"
        >
          <el-tree-select
            v-model="editForm.productCategoryId"
            disabled
            class="common-content-width"
            node-key="id"
            :props="{ label: 'categoryName', value: 'id' }"
            :data="categoryTree"
          />
        </el-form-item>
        <el-form-item
          label="商品名称"
          prop="name"
        >
          <el-popover
            placement="right-start"
            :width="300"
            trigger="hover"
            :content="editForm.name"
          >
            <template #reference>
              <el-input
                v-model="editForm.name"
                disabled
                class="common-content-width"
                maxlength="100"
                show-word-limit
              />
            </template>
          </el-popover>
        </el-form-item>

        <el-form-item
          label="市场价"
          prop="originalPrice"
        >
          <el-input
            v-model="editForm.originalPrice"
            disabled
            class="common-content-width"
            :min="0"
            :max="9999999999"
          >
            <template #append>
              元
            </template>
          </el-input>
        </el-form-item>
      </div>
      <!-- 优惠券 -->
      <coupon-card-form
        v-if="editForm.type == 'discountCoupon'"
        ref="couponCardFormRef"
      />

      <el-form-item
        label="商品图片"
        prop="bannerImages"
      >
        <template v-if="productImgList.length > 0">
          <img
            v-for="item in productImgList"
            :src="item"
            alt=""
            srcset=""
            style="width: 80px;height:80px;margin-right:10px;"
          >
        </template>
      </el-form-item>

      <el-form-item
        label="商品参数"
        prop="specification"
      >
        <el-table :data="specificationData">
          <el-table-column
            label="参数类型"
            prop="variableLabel"
          >
            <template #default="scope">
              <el-input
                v-model.trim="scope.row.variableLabel"
                disabled
                show-word-limit
                maxlength="15"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="录入参数"
            prop="variableValue"
          >
            <template #default="scope">
              <el-input
                v-model.trim="scope.row.variableValue"
                disabled
                show-word-limit
                maxlength="15"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item
        label="商品规格"
        prop="products"
      >
        <el-table :data="editForm.products">
          <el-table-column
            label="规格Code"
            prop="subCode"
            width="180"
          >
            <template #header>
              <span style="color: red">*</span>
              {{ editForm.type == 'discountCoupon' ? "批次号" : '规格Code' }}
            </template>
            <template #default="scope">
              <el-input
                v-model.trim="scope.row.subCode"
                disabled
                class="hide-suffix"
                placeholder="请输入规格Code"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="规格名称"
            prop="name"
            width="180"
          >
            <template #header>
              <span style="color: red">*</span>规格名称
            </template>
            <template #default="scope">
              <el-popover
                placement="right-start"
                :width="300"
                trigger="hover"
                :content="scope.row.name"
              >
                <template #reference>
                  <el-input
                    v-model.trim="scope.row.name"
                    disabled
                    class="hide-suffix"
                    placeholder="请输入规格名称"
                    show-word-limit
                    maxlength="100"
                  />
                </template>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column
            label="规格图片"
            prop="thumbnailUrl"
            width="180"
          >
            <template #header>
              <span style="color: red">*</span>规格图片
            </template>
            <template #default="scope">
              <upload
                v-model:model-value="scope.row.thumbnailUrl"
                list-type="picture-card"
                :limit="1"
              >
                <template #default>
                  <el-icon>
                    <plus />
                  </el-icon>
                </template>
              </upload>
            </template>
          </el-table-column>
          <el-table-column
            label="供货价"
            prop="payPrice"
            width="200"
          >
            <template #header>
              <span style="color: red">*</span>供货价
            </template>
            <template #default="scope">
              <el-input
                v-model="scope.row.payPrice"
                disabled
                class="hide-suffix"
                placeholder="请输入供货价"
                type="number"
              >
                <template #append>
                  元
                </template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="市场价"
            prop="originalPrice"
            width="200"
          >
            <template #header>
              <span style="color: red">*</span>市场价
            </template>
           
            <template #default="scope">
              <el-input
                v-model="scope.row.originalPrice"
                class="hide-suffix"
                placeholder="请输入市场价格"
                type="number"
                disabled
              >
                <template #append>
                  元
                </template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="库存"
            prop="stock"
            width="200"
          >
            <template #header>
              <span style="color: red">*</span>库存
            </template>
            <template #default="scope">
              <el-input
                v-model="scope.row.stock"
                disabled
                class="hide-suffix"
                placeholder="请输入库存"
                type="number"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="总库存">
        {{ editForm.totalStock }}
      </el-form-item>
      <el-form-item label="剩余库存">
        {{ editForm.currentStock }}
      </el-form-item>

      <el-form-item
        label="使用说明"
        prop="description"
      >
        <!-- <el-input
          v-model="editForm.description"
          disabled
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 15 }"
        /> -->
        <div
          class="text-box"
          v-html="formatStr(editForm.description)"
        />
      </el-form-item>

      <el-form-item
        label="商品图文介绍"
        prop="detailText"
      >
        <div
          class="text-box"
          v-html="formatStr(editForm.detailText)"
        />
      </el-form-item>
    </el-form>
    <el-dialog
      v-model="statusFormVisible"
      class="status-form"
      title="商品审核"
      width="50%"
      :before-close="resetStatusForm"
    >
      <el-form
        ref="statusMerchantForm"
        :model="statusForm"
        :rules="statusRules"
        label-width="120px"
      >
        <el-form-item
          label="原因"
          prop="status"
        >
          <el-radio-group
            v-model="statusForm.status"
            class="ml-4"
          >
            <el-radio
              label="1"
              size="small"
            >
              通过
            </el-radio>
            <el-radio
              label="2"
              size="small"
            >
              拒绝
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="原因"
          prop="remark"
        >
          <el-input
            v-model.trim="statusForm.remark"
            autocomplete="off"
            placeholder="请填写原因"
            maxlength="100"
            show-word-limit
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetStatusForm()">取消</el-button>
          <el-button
            type="primary"
            @click="submitStatusForm(statusMerchantForm)"
          >保存</el-button>
        </span>
      </template>
    </el-dialog>
  </main-content>
</template>

<script lang="ts" setup>
import { Ref } from "vue";
import { FormInstance } from "element-plus";
import { useGetGoodsType } from "@/components/goodsCenter/compositions/useGetGoodsType";
import { debounce } from "@/utils/index";
import CouponCardForm from "./CouponCardForm.vue";
import { goodsApplyInfo, getCategory, goodsApply } from "@/api/verify";
const statusMerchantForm = ref<FormInstance>();
const couponCardFormRef = ref()

const route = useRoute();

const router = useRouter();
const { productTypes } = useGetGoodsType();


const editFormRef = ref<FormInstance>();
const editForm = reactive({
  type: "",
  productCategoryId: null,
  thumbnailUrl: "",
  detailText: "",
  description: "",
  subCode: "",
  name: "",
  specification: "",
  originalPrice: 0,
  products: [],
  bannerImages: "",
  totalStock: '',
  currentStock: ''
});

//商品图文是否仅仅预览
const flag = ref(true)
const categoryTree = ref([])

//上传多图处理
const productImgList = computed<string[]>({
  get() {
    return editForm.bannerImages ? editForm.bannerImages.split(",") : [];
  },
  set(val: string | string[]) {
    editForm.bannerImages = val instanceof Array ? val.toString() : "";
    editForm.thumbnailUrl = val instanceof Array ? val[0] : "";
  },
});

// 商品参数 参数类型输入框绑定值
const addSpecificationModel = ref("");
// 商品参数factory
const makeSpecificationRow = (
  existingData
) => {
  const key = Object.keys(existingData)[0];
  const value = Object.values(existingData)[0];

  return {
    variableLabel: key,
    variableValue: value,
  };
};
// 商品参数表格数据
const specificationData = ref([]);
// 直接格式化表格结构为JSON到editForm中
const debounceStringifySpecData = debounce(() => {
  const specArr = specificationData.value.map((item: any) => {
    return { [item.variableLabel]: item.variableValue };
  });
  editForm.specification = JSON.stringify(specArr);
}, 700, true);
watch(
  specificationData,
  (newVal) => {
    debounceStringifySpecData(newVal);
  },
  { deep: true }
);

const applyInfoList: any = ref([])
const _getProductDetail = async () => {
  if (!route.query.id) {
    return;
  }
  const rs: any = await goodsApplyInfo({ id: route.query.id as string });

  if (rs.code !== 200) {
    return;
  }

  if (rs.payload) {
    applyInfoList.value = rs.payload;
    const applyInfo = JSON.parse(rs.payload.applyInfo)
    console.log(applyInfo)
    Object.keys(applyInfo).forEach((key) => {
      editForm[key] = applyInfo?.[key];
    });

    editForm.originalPrice = (editForm.originalPrice ?? 0) / 100;
    // editForm.payPrice = (editForm.payPrice ?? 0) / 100;

    //处理之前单图上传的回显
    if (editForm.thumbnailUrl && !editForm.bannerImages) {
      editForm.bannerImages = editForm.thumbnailUrl;
    }
    echoProducts();
    echoSpecificationData(applyInfo.specification);
    echoDetailImg(applyInfo.detailText);

    //填充卡券数据
    if (editForm.type == 'discountCoupon') {
      nextTick(() => {
        couponCardFormRef.value.getFormData(editForm.goodsInfoExt, editForm.name)
      })
    }
  }
};
const getCategoryTree = async () => {
  const rs: any = await getCategory({});
  if (rs.code == 200) {
    categoryTree.value = rs.payload
  }
}
const echoProducts = () => {
  editForm.products?.forEach((prodcut) => {
    if (prodcut.originalPrice !== undefined && !isNaN(prodcut.originalPrice)) {
      prodcut.originalPrice = prodcut.originalPrice / 100;
    }
    if (prodcut.payPrice !== undefined && !isNaN(prodcut.payPrice)) {
      prodcut.payPrice = prodcut.payPrice / 100;
    }
  });
};

const echoSpecificationData = (specification: string) => {
  try {
    const specList = JSON.parse(specification);
    specificationData.value = specList.map((item: object) =>
      makeSpecificationRow(item)
    );
  } catch (e) {
    console.log("商品参数可能空缺，转换失败：", e);
    specificationData.value = [];
  }
};

const initialDetailText = ref("");
const echoDetailImg = (detailText: string) => {
  initialDetailText.value = detailText ?? "";
};

//替换富文本字符
const formatStr = (str) => {
  return str.replaceAll(/\\n/g, '')
}
//审核逻辑
let statusForm = ref({
  status: '',
  remark: "",
});
const statusFormVisible = ref(false);
const statusRules = reactive({
  status: [
    {
      message: "请选择",
      required: true,
      trigger: "blur",
    },
  ],
  remark: [
    {
      message: "请填写原因",
      validator: (rule: any, value: any, callback: any) => {
        if (statusForm.value.status == 2 && value === '') {
          callback(new Error("请填写原因"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
});
const resetStatusForm = () => {
  statusForm.value = {
    status: '',
    remark: "",
  };
  statusMerchantForm.value?.resetFields();
  statusFormVisible.value = false;
};
const getVerifyStatus = (status: any) => {
  if (status == 0) {
    return "待审核"
  } else if (status == 1) {
    return "通过"
  } else if (status == 2) {
    return "拒绝"
  } else {
    return ""
  }
}
const submitStatusForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      let params = {
        id: route.query.id as string,
        status: statusForm.value.status,
        remark: statusForm.value.remark,
      };
      const rs: any = await goodsApply(params);
      if (rs.code == 200) {
        resetStatusForm()
        ElMessage({
          message: "审核成功！",
          type: "success",
        });
        router.push('/merchant/verify/goods')
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
const toVerify = () => {
  statusFormVisible.value = true;
}
onMounted(() => {
  _getProductDetail();
  getCategoryTree();
});

onBeforeUnmount(() => {
});
</script>

<style scoped lang="scss">
:deep(.el-form-item__content) {
  width: 100%;
}

.hide-suffix:deep(.el-input__validateIcon) {
  display: none;
}

.form-inline-row {
  margin-bottom: 5px;
}

.rich-editor-compo {
  width: 100%;
}

.common-content-width {
  width: 300px;
}

.text-box {
  overflow-y: auto;
  width: 100%;
  height: 48vh;
  border: 1px solid var(--el-border-color);
}

.question-icon {
  position: absolute;
  right: -16px;
  top: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 12px;
  height: 12px;
  margin-left: 4px;
  font-size: 10px;
  color: var(--el-text-color-regular);
  border-radius: 50%;
  border: 1px solid var(--el-text-color-regular);
}

.verify-form {
  height: 80px;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 20px;
  box-sizing: border-box;
  justify-content: space-between;
  box-shadow: 0px 1px 12px 0px rgba(0, 0, 0, 0.06), inset 0px -1px 0px 0px #ebedf0;

  .verify-form-status {
    display: flex;
    align-items: center;

    >p {
      // height: 55px;
      font-size: 16px;
      // line-height: 40px;
      margin-right: 10px;
    }

    div {
      p {
        font-size: 12px;
      }
    }

    .big {
      font-weight: bold;
      font-size: 24px;
    }
  }
}
</style>
